package com.hqq.rabbitmq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * 广播消息模式的配置类：可以将多个队列绑定到同一个交换机（FanoutExchange）上，
 * 注意广播消息模板在绑定队列到交换机上时，是不需要指定路由key的（就算指定了也不生效）。
 *
 * @author huangqiqin
 * @date 2021/04/19 00:15
 **/
@Configuration
public class FanoutConfig {

    @Autowired
    private Environment env;

    /**
     * 创建第一个队列：广播模式
     * @return
     */
    @Bean(name = "fanoutQueueOne")
    public Queue fanoutQueueOne(){
        return new Queue(env.getProperty("mq.fanout.queue.one.name"), true);
    }

    /**
     * 创建第二个队列：广播模式
     * @return
     */
    @Bean(name = "fanoutQueueTwo")
    public Queue fanoutQueueTwo(){
        return new Queue(env.getProperty("mq.fanout.queue.two.name"), true);
    }

    /**
     * 创建交换机：广播模式
     * @return
     */
    @Bean(name = "fanoutExchange")
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange(env.getProperty("mq.fanout.exchange.name"), true, false);
    }

    /**
     * 创建绑定：将队列fanoutQueueOne绑定到fanoutExchange（广播消息）交换机上
     * @return
     */
    @Bean(name = "fanoutBindingOne")
    public Binding fanoutBindingOne(Queue fanoutQueueOne, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueueOne).to(fanoutExchange);
    }

    /**
     * 创建绑定：将队列fanoutQueueTwo绑定到fanoutExchange（广播消息）交换机上
     * @return
     */
    @Bean(name = "fanoutBindingTwo")
    public Binding fanoutBindingTwo(Queue fanoutQueueTwo, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueueTwo).to(fanoutExchange);
    }

}
